<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员配置 - xyUser System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <link href="../styles/common.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .container {
            margin: 20px auto;
        }

        /* Header styles are now in common.css */

        /* Navigation styles are now in common.css */

        .content {
            padding: 20px;
        }

        .card {
            background: #f8f9fa;
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            margin-bottom: 30px;
            overflow: hidden;
        }

        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            font-weight: 600;
            font-size: 1.2em;
            padding: 20px;
        }

        .card-body {
            padding: 30px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #555;
            font-size: 16px;
        }

        .form-control, .form-select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
            background: white;
        }

        .form-control:focus, .form-select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .mb-3 {
            margin-bottom: 20px;
        }

        .btn {
            border: none;
            padding: 12px 25px;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .btn-danger {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
        }

        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(220, 53, 69, 0.3);
        }

        .btn-outline-primary {
            background: transparent;
            color: #667eea;
            border: 2px solid #667eea;
        }

        .btn-outline-primary:hover {
            background: #667eea;
            color: white;
        }

        .btn-outline-secondary {
            background: rgba(255,255,255,0.2);
            color: white;
            border: 2px solid rgba(255,255,255,0.3);
        }

        .btn-outline-secondary:hover {
            background: rgba(255,255,255,0.3);
            color: white;
        }

        .btn-sm {
            padding: 8px 15px;
            font-size: 14px;
        }

        .table {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .table th {
            background: #f8f9fa;
            color: #333;
            font-weight: 600;
            border: none;
            padding: 15px;
        }

        .table td {
            padding: 15px;
            border: none;
            border-bottom: 1px solid #e9ecef;
        }

        .table-striped tbody tr:nth-of-type(odd) {
            background-color: #f8f9fa;
        }

        .level-badge {
            display: inline-block;
            padding: 0.4em 0.8em;
            font-size: 12px;
            font-weight: 700;
            line-height: 1;
            text-align: center;
            white-space: nowrap;
            vertical-align: baseline;
            border-radius: 15px;
            margin-left: 5px;
        }

        .level-1 { background: linear-gradient(135deg, #28a745 0%, #20c997 100%); color: white; }
        .level-2 { background: linear-gradient(135deg, #17a2b8 0%, #20c997 100%); color: white; }
        .level-3 { background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%); color: white; }
        .level-4 { background: linear-gradient(135deg, #dc3545 0%, #e83e8c 100%); color: white; }

        .modal-content {
            border-radius: 15px;
            border: none;
            box-shadow: 0 20px 40px rgba(0,0,0,0.2);
        }

        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 15px 15px 0 0;
        }

        .modal-body {
            padding: 30px;
        }

        .modal-footer {
            border: none;
            padding: 20px 30px;
        }
        
        /* 确保模态框有足够高的z-index并居中显示 */
        .modal {
            z-index: 9999 !important;
        }
        
        .modal-backdrop {
            z-index: 9998 !important;
        }
        
        .modal-dialog {
            max-width: 90vw !important;
        }

        .btn-close {
            filter: invert(1);
        }

        .form-text {
            color: #6c757d;
            font-size: 14px;
        }

        /* 导航按钮样式覆盖 - 美观的UI设计 */
        .nav-pills .nav-link {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%) !important;
            color: #495057 !important;
            border: 2px solid #dee2e6 !important;
            pointer-events: auto !important;
            cursor: pointer !important;
            text-decoration: none !important;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
            transition: all 0.3s ease !important;
        }
        
        .nav-pills .nav-link:hover {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
            color: white !important;
            border-color: #667eea !important;
            text-decoration: none !important;
            transform: translateY(-2px) !important;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3) !important;
        }
        
        .nav-pills .nav-link.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
            color: white !important;
            border-color: #667eea !important;
            text-decoration: none !important;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4) !important;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 10px;
            }
            
            .header {
                padding-top: 10px;
                padding-left: 10px;
                padding-right: 10px;
                padding-bottom: 3px;
            }
            
            .header h1 {
                font-size: 2em;
                margin-bottom: 0.25rem;
            }
            
            .user-info {
                position: static;
                margin-top: 20px;
                justify-content: center;
            }
            
            .content {
                padding: 20px;
            }
            
            .card-body {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <i class="bi bi-gear-fill me-2"></i>
                xyUser System
            </a>
            <div class="ms-auto me-0">
                <span id="username" class="text-white me-3"></span>
                <span id="level-badge" class="level-badge me-3"></span>
                <button id="logout-btn" class="btn btn-outline-light btn-sm">
                    <i class="bi bi-box-arrow-right me-1"></i>
                    退出登录
                </button>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="header">
            <div class="d-flex justify-content-between align-items-center mb-1">
                <div>
                    <h1>
                        <i class="bi bi-people-fill me-3"></i>
                        管理员配置
                    </h1>
                    <p class="mb-0">管理系统用户和权限设置</p>
                </div>
            </div>
            
            <div class="mb-1">
                <nav class="nav nav-pills">
                    <a class="nav-link" href="form-config-management.html">
                        <i class="bi bi-ui-checks me-2"></i>
                        表单字段配置
                    </a>
                    <a class="nav-link" href="project-management.html">
                        <i class="bi bi-folder me-2"></i>
                        项目管理
                    </a>
                </nav>
            </div>
        </div>
        
        <div class="content">
            <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <i class="bi bi-person-plus me-2"></i>
                        创建新管理员
                    </div>
                    <div class="card-body">
                        <form id="create-admin-form">
                            <div class="mb-3">
                                <label for="username" class="form-label">用户名</label>
                                <input type="text" class="form-control" id="new-username" required>
                            </div>
                            <div class="mb-3">
                                <label for="password" class="form-label">密码</label>
                                <input type="password" class="form-control" id="new-password" required>
                            </div>
                            <div class="mb-3">
                                <label for="level" class="form-label">用户级别</label>
                                <select class="form-select" id="new-level" required onchange="handleLevelChange()">
                                    <option value="1">级别 1 (系统管理员)</option>
                                    <option value="2">级别 2 (高级管理员)</option>
                                    <option value="3">级别 3 (普通管理员)</option>
                                    <option value="4">级别 4 (数据录入员)</option>
                                </select>
                            </div>
                            <div class="mb-3" id="parent-select-container" style="display: none;">
                                <label for="parent-id" class="form-label">上级管理员</label>
                                <select class="form-select" id="parent-id">
                                    <!-- 上级管理员选项将通过JavaScript动态加载 -->
                                </select>
                                <small class="form-text text-muted">选择此用户的直接上级管理员</small>
                            </div>
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-plus-circle me-2"></i>
                                创建管理员
                            </button>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <i class="bi bi-list-ul me-2"></i>
                        管理员列表
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>用户名</th>
                                        <th>级别</th>
                                        <th>上级管理员</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="admin-list">
                                    <!-- 管理员列表将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

            <div class="mt-4">
                <a href="admin.html" class="btn btn-outline-primary">
                    <i class="bi bi-arrow-left me-2"></i>
                    返回管理面板
                </a>
            </div>
        </div>
    </div>

    <!-- 修改用户级别的模态框 -->
    <div class="modal fade" id="editLevelModal" tabindex="-1" aria-labelledby="editLevelModalLabel" aria-hidden="true" data-bs-backdrop="false">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editLevelModalLabel">修改用户级别</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="edit-level-form">
                        <input type="hidden" id="edit-user-id">
                        <div class="mb-3">
                            <label for="edit-level" class="form-label">用户级别</label>
                            <select class="form-select" id="edit-level" required>
                                <option value="1">级别 1 (系统管理员)</option>
                                <option value="2">级别 2 (高级管理员)</option>
                                <option value="3">级别 3 (普通管理员)</option>
                                <option value="4">级别 4 (数据录入员)</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="save-level-btn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 检查用户是否已登录
        function checkAuth() {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = 'login.html';
                return;
            }
            
            // 获取用户信息
            fetch('/users/profile', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('未授权');
                }
                return response.json();
            })
            .then(user => {
                // 只允许级别1的用户访问此页面
                if (user.level !== 1) {
                    alert('您没有权限访问此页面');
                    window.location.href = 'admin.html';
                    return;
                }
                
                // 显示用户信息
                document.getElementById('username').textContent = user.username;
                const levelBadge = document.getElementById('level-badge');
                levelBadge.textContent = `级别 ${user.level}`;
                levelBadge.className = `level-badge level-${user.level}`;
                
                // 加载管理员列表
                loadAdminList();
            })
            .catch(error => {
                console.error('获取用户信息失败:', error);
                localStorage.removeItem('token');
                window.location.href = 'login.html';
            });
        }

        // 加载管理员列表
        function loadAdminList() {
            const token = localStorage.getItem('token');
            fetch('/users', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => response.json())
            .then(users => {
                const adminList = document.getElementById('admin-list');
                adminList.innerHTML = '';
                
                users.forEach(user => {
                    const row = document.createElement('tr');
                    
                    const idCell = document.createElement('td');
                    idCell.textContent = user.id;
                    
                    const usernameCell = document.createElement('td');
                    usernameCell.textContent = user.username;
                    
                    const levelCell = document.createElement('td');
                    const levelBadge = document.createElement('span');
                    levelBadge.textContent = `级别 ${user.level}`;
                    levelBadge.className = `level-badge level-${user.level}`;
                    levelCell.appendChild(levelBadge);
                    
                    // 上级管理员信息
                    const parentCell = document.createElement('td');
                    if (user.parent) {
                        parentCell.textContent = `${user.parent.username} (级别 ${user.parent.level})`;
                    } else {
                        parentCell.textContent = '无上级';
                        parentCell.className = 'text-muted';
                    }
                    
                    const actionsCell = document.createElement('td');
                    
                    // 编辑按钮
                    const editBtn = document.createElement('button');
                    editBtn.className = 'btn btn-sm btn-outline-primary me-2';
                    editBtn.textContent = '修改级别';
                    editBtn.onclick = () => openEditModal(user);
                    
                    // 删除按钮
                    const deleteBtn = document.createElement('button');
                    deleteBtn.className = 'btn btn-sm btn-outline-danger';
                    deleteBtn.textContent = '删除';
                    deleteBtn.onclick = () => deleteUser(user.id);
                    
                    actionsCell.appendChild(editBtn);
                    actionsCell.appendChild(deleteBtn);
                    
                    row.appendChild(idCell);
                    row.appendChild(usernameCell);
                    row.appendChild(levelCell);
                    row.appendChild(parentCell);
                    row.appendChild(actionsCell);
                    
                    adminList.appendChild(row);
                });
            })
            .catch(error => {
                console.error('加载管理员列表失败:', error);
                alert('加载管理员列表失败');
            });
        }

        // 打开编辑模态框
        function openEditModal(user) {
            document.getElementById('edit-user-id').value = user.id;
            document.getElementById('edit-level').value = user.level;
            
            const editLevelModal = new bootstrap.Modal(document.getElementById('editLevelModal'));
            editLevelModal.show();
        }

        // 保存用户级别
        document.getElementById('save-level-btn').addEventListener('click', function() {
            const userId = parseInt(document.getElementById('edit-user-id').value);
            const newLevel = parseInt(document.getElementById('edit-level').value);
            
            // 验证级别修改的合理性
            validateLevelChange(userId, newLevel)
                .then(isValid => {
                    if (!isValid) {
                        return;
                    }
                    
                    const token = localStorage.getItem('token');
                    fetch(`/users/${userId}`, {
                        method: 'PATCH',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${token}`
                        },
                        body: JSON.stringify({ level: newLevel })
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('更新失败');
                        }
                        return response.json();
                    })
                    .then(() => {
                        bootstrap.Modal.getInstance(document.getElementById('editLevelModal')).hide();
                        loadAdminList();
                        alert('用户级别已更新');
                    })
                    .catch(error => {
                        console.error('更新用户级别失败:', error);
                        alert('更新用户级别失败');
                    });
                })
                .catch(error => {
                    console.error('验证级别修改失败:', error);
                    alert('验证级别修改失败');
                });
        });
        
        // 验证级别修改的合理性
        async function validateLevelChange(userId, newLevel) {
            const token = localStorage.getItem('token');
            
            try {
                // 获取所有用户信息
                const response = await fetch('/users', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                const users = await response.json();
                
                // 找到要修改的用户
                const targetUser = users.find(user => user.id === userId);
                if (!targetUser) {
                    alert('用户不存在');
                    return false;
                }
                
                // 如果是1级管理员，不允许修改级别
                if (targetUser.level === 1) {
                    alert('不能修改系统管理员的级别');
                    return false;
                }
                
                // 如果要修改为1级管理员，检查是否已存在1级管理员
                if (newLevel === 1) {
                    const existingLevel1 = users.filter(user => user.level === 1 && user.id !== userId);
                    if (existingLevel1.length > 0) {
                        alert('系统中已存在1级管理员，不能创建多个1级管理员');
                        return false;
                    }
                }
                
                // 检查是否有下级管理员
                const subordinates = users.filter(user => user.parent && user.parent.id === userId);
                if (subordinates.length > 0) {
                    // 找到最低级别的下级
                    const minSubordinateLevel = Math.min(...subordinates.map(sub => sub.level));
                    
                    // 不能将级别修改为等于或低于下级的级别
                    if (newLevel >= minSubordinateLevel) {
                        alert(`不能将级别修改为 ${newLevel}，因为存在级别为 ${minSubordinateLevel} 的下级管理员`);
                        return false;
                    }
                }
                
                return true;
            } catch (error) {
                console.error('验证级别修改时出错:', error);
                alert('验证级别修改时出错');
                return false;
            }
        }

        // 删除用户
        function deleteUser(userId) {
            // 验证删除的合理性
            validateUserDeletion(userId)
                .then(isValid => {
                    if (!isValid) {
                        return;
                    }
                    
                    if (!confirm('确定要删除此用户吗？此操作不可撤销。')) {
                        return;
                    }
                    
                    const token = localStorage.getItem('token');
                    fetch(`/users/${userId}`, {
                        method: 'DELETE',
                        headers: {
                            'Authorization': `Bearer ${token}`
                        }
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('删除失败');
                        }
                        loadAdminList();
                        alert('用户已删除');
                    })
                    .catch(error => {
                        console.error('删除用户失败:', error);
                        alert('删除用户失败');
                    });
                })
                .catch(error => {
                    console.error('验证删除用户失败:', error);
                    alert('验证删除用户失败');
                });
        }
        
        // 验证用户删除的合理性
        async function validateUserDeletion(userId) {
            const token = localStorage.getItem('token');
            
            try {
                // 获取所有用户信息
                const response = await fetch('/users', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                const users = await response.json();
                
                // 找到要删除的用户
                const targetUser = users.find(user => user.id === parseInt(userId));
                if (!targetUser) {
                    alert('用户不存在');
                    return false;
                }
                
                // 如果是1级管理员，不允许删除
                if (targetUser.level === 1) {
                    alert('不能删除系统管理员');
                    return false;
                }
                
                // 检查是否有下级管理员
                const subordinates = users.filter(user => user.parent && user.parent.id === parseInt(userId));
                if (subordinates.length > 0) {
                    const subordinateNames = subordinates.map(sub => sub.username).join('、');
                    alert(`不能删除此管理员，因为存在下级管理员：${subordinateNames}`);
                    return false;
                }
                
                return true;
            } catch (error) {
                console.error('验证删除用户时出错:', error);
                alert('验证删除用户时出错');
                return false;
            }
        }

        // 根据选择的级别显示或隐藏上级管理员选择
        function handleLevelChange() {
            const level = parseInt(document.getElementById('new-level').value);
            const parentContainer = document.getElementById('parent-select-container');
            
            // 级别1不需要上级，级别2-4需要上级
            if (level === 1) {
                parentContainer.style.display = 'none';
            } else {
                parentContainer.style.display = 'block';
                loadPotentialParents(level);
            }
        }
        
        // 加载可选的上级管理员
        function loadPotentialParents(childLevel) {
            const token = localStorage.getItem('token');
            const parentSelect = document.getElementById('parent-id');
            
            // 清空现有选项
            parentSelect.innerHTML = '';
            
            fetch('/users', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => response.json())
            .then(users => {
                // 根据树状结构筛选可选的上级管理员
                let potentialParents = [];
                
                if (childLevel === 2) {
                    // 2级管理员只能选择1级管理员作为上级
                    potentialParents = users.filter(user => user.level === 1);
                } else if (childLevel === 3) {
                    // 3级管理员只能选择2级管理员作为上级
                    potentialParents = users.filter(user => user.level === 2);
                } else if (childLevel === 4) {
                    // 4级管理员只能选择3级管理员作为上级
                    potentialParents = users.filter(user => user.level === 3);
                }
                
                if (potentialParents.length === 0) {
                    const option = document.createElement('option');
                    option.textContent = `没有可选的级别 ${childLevel - 1} 管理员`;
                    option.disabled = true;
                    option.selected = true;
                    parentSelect.appendChild(option);
                } else {
                    // 添加默认选项
                    const defaultOption = document.createElement('option');
                    defaultOption.value = '';
                    defaultOption.textContent = '-- 请选择上级管理员 --';
                    defaultOption.selected = true;
                    parentSelect.appendChild(defaultOption);
                    
                    // 添加所有可选上级
                    potentialParents.forEach(parent => {
                        const option = document.createElement('option');
                        option.value = parent.id;
                        option.textContent = `${parent.username} (级别 ${parent.level})`;
                        parentSelect.appendChild(option);
                    });
                }
            })
            .catch(error => {
                console.error('加载上级管理员失败:', error);
                const option = document.createElement('option');
                option.textContent = '加载上级管理员失败';
                option.disabled = true;
                option.selected = true;
                parentSelect.appendChild(option);
            });
        }

        // 创建新管理员
        document.getElementById('create-admin-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const username = document.getElementById('new-username').value;
            const password = document.getElementById('new-password').value;
            const level = parseInt(document.getElementById('new-level').value);
            
            // 如果是1级管理员，检查是否已存在
            if (level === 1) {
                const token = localStorage.getItem('token');
                fetch('/users', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                })
                .then(response => response.json())
                .then(users => {
                    const existingLevel1 = users.filter(user => user.level === 1);
                    if (existingLevel1.length > 0) {
                        alert('系统中已存在1级管理员，不能创建多个1级管理员');
                        return;
                    }
                    // 如果没有1级管理员，继续创建
                    createUser({ username, password, level });
                })
                .catch(error => {
                    console.error('检查1级管理员失败:', error);
                    alert('检查1级管理员失败');
                });
                return;
            }
            
            // 构建请求数据
            const userData = { username, password, level };
            
            // 如果不是级别1，则需要添加上级管理员ID
            if (level > 1) {
                const parentId = document.getElementById('parent-id').value;
                if (!parentId) {
                    alert('请选择上级管理员');
                    return;
                }
                userData.parentId = parseInt(parentId);
            }
            
            createUser(userData);
        });
        
        // 创建用户的通用函数
        function createUser(userData) {
            const token = localStorage.getItem('token');
            fetch('/users', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(userData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('创建失败');
                }
                return response.json();
            })
            .then(() => {
                document.getElementById('create-admin-form').reset();
                document.getElementById('parent-select-container').style.display = 'none';
                loadAdminList();
                alert('管理员创建成功');
            })
            .catch(error => {
                console.error('创建管理员失败:', error);
                alert('创建管理员失败，可能用户名已存在');
            });
        }

        // 退出登录
        document.getElementById('logout-btn').addEventListener('click', function() {
            localStorage.removeItem('token');
            window.location.href = 'login.html';
        });

        // 页面加载时检查认证
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            // 初始化上级管理员选择框的显示状态
            handleLevelChange();
        });
    </script>
</body>
</html>